<template>
  <div class="resume-test">
    <div class="test-header">
      <h1>简历功能测试</h1>
      <p>测试简历的预览和下载功能</p>
    </div>

    <div class="test-content">
      <el-card class="test-card">
        <template #header>
          <div class="card-header">
            <span>简历功能测试</span>
            <el-button type="primary" @click="refreshData">刷新数据</el-button>
          </div>
        </template>

        <div class="test-section">
          <h3>测试简历信息</h3>
          <div v-if="testResume" class="resume-info">
            <p><strong>简历ID:</strong> {{ testResume.id }}</p>
            <p><strong>标题:</strong> {{ testResume.title }}</p>
            <p><strong>类型:</strong> {{ testResume.resume_type }}</p>
            <p><strong>完成度:</strong> {{ testResume.completion_rate }}%</p>
            <p><strong>状态:</strong> {{ testResume.status }}</p>
            <p><strong>生成文件URL:</strong> {{ testResume.generated_file_url || '无' }}</p>
            <p><strong>生成文件名:</strong> {{ testResume.generated_file_name || '无' }}</p>
          </div>
          <div v-else>
            <el-alert title="未找到测试简历" type="warning" />
          </div>
        </div>

        <div class="test-section">
          <h3>功能测试</h3>
          <div class="test-buttons">
            <el-button 
              type="primary" 
              @click="testPreview"
              :disabled="!canPreview"
            >
              测试预览功能
            </el-button>
            
            <el-button 
              type="success" 
              @click="testDownload"
              :disabled="!canDownload"
            >
              测试下载功能
            </el-button>
            
            <el-button 
              type="info" 
              @click="testGenerate"
            >
              测试生成功能
            </el-button>
            
            <el-button 
              type="warning" 
              @click="updateCompletion"
            >
              更新完成度
            </el-button>
          </div>
        </div>

        <div class="test-section">
          <h3>测试结果</h3>
          <div class="test-results">
            <div v-for="result in testResults" :key="result.id" class="test-result">
              <el-tag :type="result.success ? 'success' : 'danger'">
                {{ result.success ? '✓' : '✗' }}
              </el-tag>
              <span class="result-text">{{ result.message }}</span>
              <span class="result-time">{{ result.time }}</span>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 预览对话框 -->
    <EnhancedResumePreview
      v-model:visible="showPreview"
      :file-url="previewUrl"
      :file-name="previewFileName"
      title="测试预览"
      @download="handlePreviewDownload"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { resumeApi } from '@/api/resume'
import EnhancedResumePreview from '@/components/EnhancedResumePreview.vue'

// 测试数据
const testResume = ref<any>(null)
const testResults = ref<any[]>([])
const showPreview = ref(false)
const previewUrl = ref('')
const previewFileName = ref('')

// 计算属性
const canPreview = computed(() => {
  if (!testResume.value) return false
  return !!(testResume.value.generated_file_url || testResume.value.generated_file)
})

const canDownload = computed(() => {
  if (!testResume.value) return false
  if (testResume.value.resume_type === 'generated') {
    return !!(testResume.value.generated_file_url || testResume.value.generated_file) ||
           parseFloat(testResume.value.completion_rate || '0') >= 80
  }
  return !!(testResume.value.uploaded_file)
})

// 添加测试结果
const addTestResult = (message: string, success: boolean) => {
  testResults.value.unshift({
    id: Date.now(),
    message,
    success,
    time: new Date().toLocaleTimeString()
  })
  
  // 只保留最近10条结果
  if (testResults.value.length > 10) {
    testResults.value = testResults.value.slice(0, 10)
  }
}

// 刷新数据
const refreshData = async () => {
  try {
    const response = await resumeApi.getResumeList({ page: 1, page_size: 10 })
    const resumes = response.data?.results || response.results || []
    
    // 找到第一个在线生成的简历
    testResume.value = resumes.find((r: any) => r.resume_type === 'generated') || resumes[0]
    
    if (testResume.value) {
      addTestResult(`成功加载测试简历: ${testResume.value.title}`, true)
    } else {
      addTestResult('未找到可测试的简历', false)
    }
  } catch (error: any) {
    addTestResult(`加载简历失败: ${error.message}`, false)
  }
}

// 测试预览功能
const testPreview = () => {
  if (!testResume.value) {
    addTestResult('没有可预览的简历', false)
    return
  }
  
  if (testResume.value.generated_file_url) {
    previewUrl.value = testResume.value.generated_file_url
    previewFileName.value = testResume.value.generated_file_name || `${testResume.value.title}.docx`
    showPreview.value = true
    addTestResult('预览功能测试成功', true)
  } else {
    addTestResult('没有可预览的文件', false)
  }
}

// 测试下载功能
const testDownload = async () => {
  if (!testResume.value) {
    addTestResult('没有可下载的简历', false)
    return
  }
  
  try {
    if (testResume.value.generated_file_url) {
      // 直接下载已生成的文件
      const downloadUrl = `/api/resume-management/resumes/${testResume.value.id}/download-generated/`
      const response = await fetch(downloadUrl, {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('access_token')}`
        }
      })
      
      if (response.ok) {
        addTestResult('下载功能测试成功', true)
      } else {
        addTestResult(`下载失败: HTTP ${response.status}`, false)
      }
    } else {
      addTestResult('没有可下载的文件', false)
    }
  } catch (error: any) {
    addTestResult(`下载测试失败: ${error.message}`, false)
  }
}

// 测试生成功能
const testGenerate = async () => {
  if (!testResume.value) {
    addTestResult('没有可生成的简历', false)
    return
  }
  
  try {
    const response = await resumeApi.generateResume(testResume.value.id, 'docx')
    addTestResult('生成功能测试成功', true)
    
    // 刷新数据
    await refreshData()
  } catch (error: any) {
    addTestResult(`生成测试失败: ${error.message}`, false)
  }
}

// 更新完成度
const updateCompletion = async () => {
  if (!testResume.value) {
    addTestResult('没有可更新的简历', false)
    return
  }
  
  try {
    // 调用后端API更新完成度
    const response = await fetch(`/api/resume-management/resumes/${testResume.value.id}/update-completion/`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('access_token')}`,
        'Content-Type': 'application/json'
      }
    })
    
    if (response.ok) {
      addTestResult('完成度更新成功', true)
      await refreshData()
    } else {
      addTestResult(`完成度更新失败: HTTP ${response.status}`, false)
    }
  } catch (error: any) {
    addTestResult(`完成度更新失败: ${error.message}`, false)
  }
}

// 处理预览下载
const handlePreviewDownload = () => {
  testDownload()
}

// 组件挂载时加载数据
onMounted(() => {
  refreshData()
})
</script>

<style lang="scss" scoped>
.resume-test {
  padding: 24px;
  background: #f5f7fa;
  min-height: 100vh;
}

.test-header {
  text-align: center;
  margin-bottom: 32px;
  
  h1 {
    font-size: 28px;
    color: #2c3e50;
    margin-bottom: 8px;
  }
  
  p {
    color: #7f8c8d;
    font-size: 16px;
  }
}

.test-content {
  max-width: 800px;
  margin: 0 auto;
}

.test-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}

.test-section {
  margin-bottom: 32px;
  
  h3 {
    color: #2c3e50;
    margin-bottom: 16px;
    font-size: 18px;
  }
}

.resume-info {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 8px;
  border-left: 4px solid #007bff;
  
  p {
    margin: 8px 0;
    
    strong {
      color: #495057;
      margin-right: 8px;
    }
  }
}

.test-buttons {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.test-results {
  max-height: 300px;
  overflow-y: auto;
  
  .test-result {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 8px 0;
    border-bottom: 1px solid #eee;
    
    .result-text {
      flex: 1;
      color: #495057;
    }
    
    .result-time {
      color: #6c757d;
      font-size: 12px;
    }
  }
}
</style>
